<template>
  <el-tooltip
    class="tooltip"
    effect="light"
    :content="tooltipContent"
    placement="right"
    :disabled="toolDisabled"
  >
    <el-select
      v-model="value"
      @change="changeSelect"
      @visible-change="visibleChange"
      :filter-method="filterMethod"
      placeholder="请选择"
      :collapse-tags="!isCollapseTags"
      size="mini"
      ref="tSelect"
      popper-class="t-select"
      class="t-select"
      :value-key="config.valueKey || 'id'"
      clearable
      filterable
      :popper-append-to-body="false"
      :multiple="config.isMultiple || false"
    >
      <!-- 表头 -->
      <div class="t-table-header">
        <table
          cellspacing="0"
          cellpadding="0"
          border="0"
          class="t-table-wrapper"
        >
          <thead>
            <tr>
              <th
                v-for="(item, index) in columns"
                :key="index"
                class="t-th"
                :style="{
                  minWidth: item.minWidth || '150px',
                  width: item.width || '150px',
                }"
              >
                <div class="t-header-txt">{{ item.label }}</div>
                <el-input
                  placeholder="请输入"
                  v-model="searchList[item.prop]"
                  @change="changeInput(searchList[item.prop], item.prop)"
                  clearable
                  size="mini"
                  class="t-header-input"
                >
                </el-input>
              </th>
            </tr>
          </thead>
        </table>
      </div>
      <!-- 表体 -->
      <div class="t-select-option">
        <el-option
          v-for="item in dataList"
          :key="item.id"
          :label="item[config.label || 'port']"
          :value="item"
        >
          <table border="1" class="t-table-wrapper">
            <tr class="t-tr" align="center">
              <td
                class="t-ceil"
                :style="{
                  minWidth: child.minWidth || '150px',
                  width: child.width || '150px',
                }"
                v-for="(child, j) in columns"
                :key="j"
              >
                {{ item[child.prop] }}
              </td>
            </tr>
          </table>
        </el-option>
      </div>
      <template #empty v-if="showReBtn">
        <div class="empty-box">
          <!-- 无匹配数据 -->
          <span>暂无匹配数据</span>
          <!-- 点击重新加载 -->
          <span class="load-text" @click="reGetDataList">点击重新加载</span>
        </div>
      </template>
      <!-- 表底部 -->
      <div class="t-bottom-page" v-if="config.isShowPagination">
        <el-pagination
          small
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount"
          :pager-count="5"
        >
        </el-pagination>
      </div>
    </el-select>
  </el-tooltip>
</template>

<script>
export default {
  props: {
    // 表头
    columns: {
      type: Array,
      default: () => {
        return [
          {
            prop: "global",
            label: "全球港口GMP",
          },
          {
            prop: "country",
            label: "国家名称",
          },
          {
            prop: "port",
            label: "港口名称",
          },
        ];
      },
    },
    // 表格数据
    data: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // 表格总条数
    total: {
      type: Number,
      default: () => {
        return 0;
      },
    },
    // 默认已选择
    checked: [String, Object, Array],
    // 配置
    config: {
      type: Object,
      default: () => {
        return {
          valueKey: "id", // 绑定的value-key, 默认为 id
          label: "port", // 展示的lable值,默认为 port
          isShowPagination: true, // 是否分页
          isMultiple: false, // 是否多选
        };
      },
    },
  },
  data() {
    return {
      dataList: [], // 表格绑定的数据
      totalCount: 0, // 表格绑定的数据的总条数
      value: "", // 绑定的值----选中的整个对象/数组
      checkedKey: "", // 绑定选中的value-key
      tooltipContent: "", // 选中的值的提示内容
      searchList: {}, // 搜索的内容
      currentPage: 1, // 当前页
      pageSize: 10, // 分页数
      isCollapseTags: false, // 是否折叠tags
      showReBtn: false, // 是否展示重新搜索按钮
    };
  },
  computed: {
    // 不展示提示框的情况: 单选,下拉框展示,tooltipContent不为空
    toolDisabled() {
      let flag =
        !this.tooltipContent || !this.config.isMultiple || this.isCollapseTags;
      return flag;
    },
  },
  watch: {
    // 监听已选择的数据,初始化处理
    checked: {
      deep: true,
      immediate: true,
      handler(v) {
        this.initCheckData();
      },
    },
    // 监听数据的变化
    data: {
      deep: true,
      immediate: true,
      handler(v) {
        if (v.length > 0) {
          this.paging();
          this.initCheckData();
        }
      },
    },
  },
  created() {
    this.paging();
  },
  methods: {
    // 选择
    changeSelect() {
      // this.$emit("selectChange", this.value);
    },
    // 模糊搜索
    changeInput(content, label) {
      let arr = this.deepClone(this.data);
      if (content) {
        this.dataList = arr.filter((item) => {
          let str = item[label] || "";
          return str.indexOf(content) !== -1;
        });
        this.totalCount = this.dataList.length;
        if (this.totalCount <= 0) {
          this.showReBtn = true;
        }
      } else {
        this.dataHandle();
      }
    },
    // 有搜索项时对表格数据的处理
    dataHandle() {
      let arr = this.deepClone(this.data);
      let flag = true;
      for (let key in this.searchList) {
        // 还有可搜索项
        if (this.searchList[key]) {
          flag = false;
          this.dataList = arr.filter((item) => {
            let str = item[key] || "";
            return str.indexOf(this.searchList[key]) !== -1;
          });
          this.totalCount = this.dataList.length;
        }
      }
      // 搜索项都为空
      if (flag) this.paging();
    },
    // 分页
    paging() {
      this.searchList = {};
      let arr = this.deepClone(this.data);
      this.totalCount = this.total;
      let start = (this.currentPage - 1) * this.pageSize;
      this.dataList = arr.splice(start, this.pageSize);
    },
    // 下拉框出现/隐藏时触发	出现则为 true，隐藏则为 false
    visibleChange(val) {
      this.isCollapseTags = val;
      this.paging();
      if (!val) {
        this.changeTooltip();
        this.$emit("selectChange", this.value, this.checkedKey);
      }
    },
    // 自定义过滤方法
    filterMethod(content) {
      if (content) {
        this.dataList = this.data.filter((item) => {
          return item[this.config.label].includes(content);
        });
        this.totalCount = this.dataList.length;
      } else {
        this.dataHandle();
      }
    },
    // 修改提示框的内容
    changeTooltip() {
      this.tooltipContent = "";
      this.checkedKey = "";
      if (this.config.isMultiple) {
        // 多选
        this.value.map((item) => {
          this.tooltipContent += item[this.config.label] + ",";
          this.checkedKey += item[this.config.valueKey] + ",";
        });
      } else {
        // 单选
        this.tooltipContent = this.value[this.config.label];
        this.checkedKey = this.value[this.config.valueKey];
      }
    },
    // 根据已选,处理数据
    initCheckData() {
      if (this.checked && this.data) {
        let newVal = [];
        newVal = Array.isArray(this.checked)
          ? this.checked
          : this.checked.split(",");
        this.checkedKey = newVal.toString();
        let arr = [];
        newVal.map((i) => {
          for (let item of this.data) {
            if (i === item[this.config.valueKey]) {
              arr.push(item);
              this.tooltipContent += item[this.config.label] + ",";
              break;
            }
          }
        });
        if (arr.length > 0) {
          if (!this.config.isMultiple) {
            this.value = arr[0];
          } else {
            this.value = arr;
          }
        }
      }
    },
    // 重新获取数据
    reGetDataList() {
      this.showReBtn = false;
      this.paging();
    },
    // 每页数
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.$refs.tSelect.focus();
      this.paging();
    },
    // 当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.$refs.tSelect.focus();
      this.paging();
    },
  },
};
</script>

<style lang="scss" scoped>
.t-tooltip {
  width: 100%;
}
.t-select {
  width: 100% !important;
  // 表头
  .t-table-header {
    position: absolute;
    width: 100%;
    top: 0;
    left: 0;
    height: 30px;
    font-size: 13px;
    font-weight: 600;
    z-index: 999;
    color: #515a6e;
    background-color: #f8f8f9;
    .t-table-wrapper {
      width: 100%;
      height: 100%;
      .t-th {
        border: 1px solid #dfe6ec !important;
        border-right: 0 !important;
        .t-header-txt:first-child {
          line-height: 25px;
          height: 25px;
          border-bottom: 1px solid #dfe6ec;
        }
        .t-header-input {
          .el-input__inner {
            padding: 0 10px;
          }
        }
      }
    }
  }
  // 表体
  .t-select-option {
    position: relative;
    .t-table-wrapper {
      width: 100%;
      border-collapse: collapse;
      border: 1px solid #dfe6ec;
    }
    .el-select-dropdown__item {
      margin-top: -1px;
      line-height: 30px;
    }
  }
  ::v-deep .el-select-dropdown__wrap {
    max-height: 409px;
  }

  // 表尾部(分页)
  .t-bottom-page {
    background-color: #f8f8f9;
    ::v-deep .el-input__inner {
      padding: 0;
    }
    .el-input__suffix {
      // margin-top: 2px;
    }
  }
}
</style>